package com.heima.wemedia.controller.v1;

import com.heima.apis.article.IArticleClient;
import com.heima.article.service.impl.ArticleServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.ArticleDto;
import com.heima.model.wemedia.dtos.NewsDto;
import com.heima.model.wemedia.pojos.Channel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.service.*;
import com.heima.wemedia.utils.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author 嘉德罗斯
 * @date 2021/11/22
 */
@RestController
@RequestMapping("/api/v1/news")
public class NewsController {

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private NewsMaterialService newsMaterialService;

    @Autowired
    private WmMaterialService wmMaterialService;


    @PostMapping("/list")
    //查看文章
    public ResponseResult list(@RequestBody NewsDto dto,HttpServletRequest request){
        Integer id = Token.getId(request);
        ResponseResult responseResult = wmNewsService.find(dto,id);
        return responseResult;
    }

    @PostMapping("/down_or_up")
    public ResponseResult down(@RequestBody Map map){
        ResponseResult responseResult = wmNewsService.down(map);
        return responseResult;
    }

    @PostMapping("/submit")
    //上传文章
    public ResponseResult submit(@RequestBody ArticleDto dto,HttpServletRequest request){
        Integer id = Token.getId(request);
        WmNews wmNews = wmNewsService.submit(dto, id);
        List<Integer> mIds = wmMaterialService.getMaterial(dto.getImages());
        boolean submit = newsMaterialService.submit(wmNews.getId(), mIds);
        if (submit){
            return ResponseResult.okResult(200,"上传成功");
        }
        return ResponseResult.errorResult(500,"失败");
    }

    @GetMapping("/one/{id}")
    //修改回显数据
    public ResponseResult echo(@PathVariable Integer id){
        return wmNewsService.echo(id);
    }

    @GetMapping("/del_news/{id}")
    //删除文章
    public ResponseResult delete(@PathVariable Integer id){
        boolean flag;
        try {
            wmNewsService.delete(id);
            newsMaterialService.delete(id);
            flag = true;
        } catch (Exception e) {
            flag = false;
        }
        if (flag){
            return ResponseResult.okResult(200,"删除成功");
        }
        return ResponseResult.errorResult(501,"服务器异常");
    }
}
